package com.bosch.in.rtp1.ept.manager.impl;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;

import com.bosch.in.rtp1.ept.dao.LotStatusDao;
import com.bosch.in.rtp1.ept.manager.LotStatusManager;
import com.bosch.in.rtp1.ept.model.dto.DurationColorCon;
import com.bosch.in.rtp1.ept.model.dto.LotStatus;
import com.bosch.in.rtp1.ept.model.technical.Condition4LotStatus;
import com.bosch.in.rtp1.ept.util.ConverterUtility;
import com.bosch.in.rtp1.ept.util.DaoFactory;
import com.bosch.in.rtp1.ept.util.ExporterUtility;
import com.bosch.in.rtp1.ept.util.ehcache.EhcacheFactory;

/**
 * Concrete implementation of LotStatusManager which provides service to manipulate 
 * LotStatus data, delegate data source retrieval and transaction management to 
 * DBConnectionManager attribute.  
 * @author TPR1HC
 *
 */
public class LotStatusManagerImpl implements LotStatusManager{
	/**
	 * used to manage connection
	 */
	private DBConnectionManager dbManager;
	/**
	 * DAO object to get LotStatus data.
	 */
	private LotStatusDao lotStatusDao;
	
	private static final Logger LOGGER = Logger.getLogger(LotStatusManagerImpl.class);
	
	private static final String PDF_PARAM_COND = "con4LotStatus";
	    
	private static final String PDF_PARAM_DATE = "reportDate";
	
	/**
	 * Look up datasource to get connection from pre-initialized connection pool
	 * @throws Exception
	 */
	public LotStatusManagerImpl() { 
	}

	/**
	 * lazy initialize connection when we really need to interact with database and in case 
	 * data can't be found in caching system.
	 * @throws SQLException
	 */
	private void init() throws SQLException {
		dbManager = new DBConnectionManager();
		lotStatusDao = DaoFactory.getInstance().getLotStatusDao(dbManager.getConnection());
	}

	@Override
	public List<LotStatus> getLotStatus(Condition4LotStatus searchCriteria) throws SQLException  {
		LOGGER.debug("Begin LotStatusManagerImpl.getLotStatus");
		try {
			// lazy init connection
			init();
			List<LotStatus> lotStatuses = lotStatusDao.getLotStatus(searchCriteria);
			
			///* caching for exporting to pdf/excel file */
	    	//EhcacheFactory.getLotStatusEhcacheWrapper().put(searchCriteria.getParameterValues().toString() + searchCriteria.getOrderBy(), lotStatuses);
	    	
	    	return lotStatuses;
		} finally {
			dbManager.close();
			LOGGER.debug("Closed connection");
			LOGGER.debug("End LotStatusManagerImpl.getLotStatus");
		}
	}
/*
	@Override
	public Workbook exportToExcel(Condition4LotStatus searchCriteria, InputStream is, DurationColorCon durCorCon) throws IOException, SQLException {
		LOGGER.debug("Begin LotStatusManagerImpl.exportToExcel");
		try {
			// Read data from Ehcache
			List<LotStatus> lotStatuses = EhcacheFactory.getLotStatusEhcacheWrapper().get(searchCriteria.getParameterValues().toString() + searchCriteria.getOrderBy());
			
			if (lotStatuses == null) {
				lotStatuses = getLotStatus(searchCriteria);
			}
			
			lotStatuses = checkSpecialFilter(searchCriteria, lotStatuses);
			
			return ExporterUtility.exportLotStatusToExcel(lotStatuses, is, searchCriteria, durCorCon);
		} finally {
			LOGGER.debug("End LotStatusManagerImpl.exportToExcel");
		}
	}
*/	
//	/**
//	 * For special field which is calculated field for rounded up number field, we
//	 * have to check these field if the search condition filter includes these fields.
//	 * @param searchCriteria
//	 * @param lotStatuses
//	 * @return
//	 */
//	private List<LotStatus> checkSpecialFilter(
//			Condition4LotStatus searchCriteria, List<LotStatus> lotStatuses) {
//		// Exclude record which doesn't match calculated filter waittime
//		if (!searchCriteria.getWaittime().isEmpty() && lotStatuses.size() > 0) { 
//			lotStatuses = extractMatchedCalculatedWaitTime(searchCriteria, lotStatuses);
//		}
//		// Exclude record which doesn't match rounded up number filter like X-Plan, X-RWH, X-RW
//		if (!searchCriteria.getX_plan().isEmpty() && lotStatuses.size() > 0) { 
//			lotStatuses = extractMatchedXPlan(searchCriteria, lotStatuses);
//		}
//		if (!searchCriteria.getX_rwh().isEmpty() && lotStatuses.size() > 0) { 
//			lotStatuses = extractMatchedXRWH(searchCriteria, lotStatuses);
//		}
//		if (!searchCriteria.getX_rw().isEmpty() && lotStatuses.size() > 0) { 
//			lotStatuses = extractMatchedXRW(searchCriteria, lotStatuses);
//		}
//		return lotStatuses;
//	}
	
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	@Override
//	public JasperPrint exportPdf(Condition4LotStatus searchCriteria, InputStream reportSource) throws SQLException, JRException {
//		// Read data from Ehcache
//		List<LotStatus> lotStatuses = EhcacheFactory
//				.getLotStatusEhcacheWrapper().get(searchCriteria.getParameterValues().toString());
//		if (lotStatuses == null) {
//			// get LotStatusManager instance
//			LotStatusManager lotStatusManager = ManagerFactory.getInstance()
//					.getLotStatusManager();
//			/* query data with search condition gotten from parameter in request */
//			lotStatuses = lotStatusManager.getLotStatus(searchCriteria);
//		}
//
//		lotStatuses = checkSpecialFilter(searchCriteria, lotStatuses);
//		
//		// define datasource for pdf content
//		JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(
//				lotStatuses);
//		
//		// populate data in datasource to report
//		Map parameters = new HashMap();
//		
//		parameters.put(PDF_PARAM_COND, searchCriteria);
//		Date today = new Date();
//		parameters.put(PDF_PARAM_DATE, today);
//		JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource,parameters, dataSource);
//		return jasperPrint;
//	}

//	private List<LotStatus> extractMatchedCalculatedWaitTime(Condition4LotStatus searchCriteria,
//			List<LotStatus> lotStatuses) {
//		List<LotStatus> result = new ArrayList<LotStatus>();
//		for (int i = 0; i < lotStatuses.size(); i++) {
//			if (String.valueOf(lotStatuses.get(i).getWaitTime()).indexOf(searchCriteria.getWaittime()) >= 0) {
//				result.add(lotStatuses.get(i));
//			}
//		}
//		return result;
//	}
//	
//	private List<LotStatus> extractMatchedXPlan(Condition4LotStatus searchCriteria,
//			List<LotStatus> lotStatuses) {
//		List<LotStatus> result = new ArrayList<LotStatus>();
//		for (int i = 0; i < lotStatuses.size(); i++) {
//			if (String.valueOf(lotStatuses.get(i).getX_plan()).indexOf(searchCriteria.getX_plan()) >= 0) {
//				result.add(lotStatuses.get(i));
//			}
//		}
//		return result;
//	}
//	
//	private List<LotStatus> extractMatchedXRWH(Condition4LotStatus searchCriteria,
//			List<LotStatus> lotStatuses) {
//		List<LotStatus> result = new ArrayList<LotStatus>();
//		for (int i = 0; i < lotStatuses.size(); i++) {
//			if (String.valueOf(lotStatuses.get(i).getX_rwh()).indexOf(searchCriteria.getX_rwh()) >= 0) {
//				result.add(lotStatuses.get(i));
//			}
//		}
//		return result;
//	}
//	
//	private List<LotStatus> extractMatchedXRW(Condition4LotStatus searchCriteria,
//			List<LotStatus> lotStatuses) {
//		List<LotStatus> result = new ArrayList<LotStatus>();
//		for (int i = 0; i < lotStatuses.size(); i++) {
//			if (String.valueOf(lotStatuses.get(i).getX_rw()).indexOf(searchCriteria.getX_rw()) >= 0) {
//				result.add(lotStatuses.get(i));
//			}
//		}
//		return result;
//	}

	@Override
	public Workbook exportToExcel(Condition4LotStatus searchCriteria,
			String jsonLotStatuses, InputStream is, DurationColorCon durCorCon)
			throws IOException, SQLException, ParseException {
		LOGGER.debug("Begin LotStatusManagerImpl.exportToExcel");
		try {
			// convert json string to LotStatus object list
			List<LotStatus> lotStatuses = ConverterUtility.convertToLotStatuses(jsonLotStatuses);
			
			return ExporterUtility.exportLotStatusToExcel(lotStatuses, is, searchCriteria, durCorCon);
		} finally {
			LOGGER.debug("End LotStatusManagerImpl.exportToExcel");
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JasperPrint exportPdf(Condition4LotStatus searchCriteria,
			String jsonLotStatuses, InputStream reportSource) throws SQLException,
			JRException, ParseException {
		LOGGER.debug("Begin LotStatusManagerImpl.exportPdf");
		// convert json string to LotStatus object list
		List<LotStatus> lotStatuses = ConverterUtility.convertToLotStatuses(jsonLotStatuses);
		
		// define datasource for pdf content
		JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(
				lotStatuses);
		
		// populate data in datasource to report
		Map parameters = new HashMap();
		
		parameters.put(PDF_PARAM_COND, searchCriteria);
		Date today = new Date();
		parameters.put(PDF_PARAM_DATE, today);
		JasperPrint jasperPrint = JasperFillManager.fillReport(reportSource,parameters, dataSource);
		return jasperPrint;
	}
}
